package client

import (
	"ZK306/common/proto/user"
	"context"
	"google.golang.org/grpc"
)

type Handle func(ctx context.Context, in user.UserClient) (interface{}, error)

func UserClient(ctx context.Context, handle Handle) (interface{}, error) {
	dial, err := grpc.Dial("127.0.0.1:8003", grpc.WithInsecure())
	if err != nil {
		return nil, err
	}
	client := user.NewUserClient(dial)
	res, err := handle(ctx, client)
	if err != nil {
		return nil, err
	}
	defer dial.Close()
	return res, nil
}

func UserLogin(ctx context.Context, i *user.UserLoginRequest) (*user.UserLoginResponse, error) {
	client, err := UserClient(ctx, func(ctx context.Context, in user.UserClient) (interface{}, error) {
		login, err := in.UserLogin(ctx, i)
		if err != nil {
			return nil, err
		}
		return login, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.UserLoginResponse), nil
}
func UserSms(ctx context.Context, i *user.UserSmsRequest) (*user.UserSmsResponse, error) {
	client, err := UserClient(ctx, func(ctx context.Context, in user.UserClient) (interface{}, error) {
		login, err := in.UserSms(ctx, i)
		if err != nil {
			return nil, err
		}
		return login, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.UserSmsResponse), nil
}
